﻿#define _CRT_SECURE_NO_WARNINGS 1

#include "List.h"
//打印
void LTPrint(LTNode* phead)
{
	assert(phead);
	LTNode* cur = phead->next;
	while (cur != phead)
	{
		printf("%d<=>", cur->data);
		cur = cur->next;
	}
	printf("\n");
}

LTNode* LTBuyNode(LTDataType x)
{
	LTNode* node = (LTNode*)malloc(sizeof(LTNode));
	if (node == NULL)
	{
		perror("malloc fail");
		exit(-1);
	}
	node->data = x;
	node->prev = node->next = NULL;

	return node;
}

//初始化
LTNode* LTInit()
{
	LTNode* head = LTBuyNode(-1);
	head->prev = head->next = head;

	return head;
}
//尾插
void LTPushBack(LTNode* phead, LTDataType x)
{
	assert(phead);
	LTNode* newNode = LTBuyNode(x);
	// phead->prev newNode phead
	newNode->prev = phead->prev;
	newNode->next = phead;

	phead->prev->next = newNode;
	phead->prev = newNode;
}
//尾删
void LTPopBack(LTNode* phead)
{
	assert(phead && phead->next != phead);
	LTNode* del = phead->prev;
	//del->prev  del  phead
	phead->prev = del->prev;
	del->prev->next = phead;
	free(del);
	del = NULL;
}
//头插
void LTPushFront(LTNode* phead, LTDataType x)
{
	assert(phead);
	LTNode* newNode = LTBuyNode(x);
	//phead newNode phead->next
	newNode->prev = phead;
	newNode->next = phead->next;

	phead->next->prev = newNode;
	phead->next = newNode;
}
//头删
void LTPopFront(LTNode* phead)
{
	assert(phead && phead->next != phead);
	LTNode* del = phead->next;
	//phead del del->next
	phead->next = del->next;
	del->next->prev = phead;
	free(del);
	del = NULL;
}
//查找
LTNode* LTFind(LTNode* phead, LTDataType x)
{
	assert(phead);
	LTNode* cur = phead->next;
	while (cur != phead)
	{
		//找到了
		if (cur->data == x)
			return cur;

		cur = cur->next;
	}
	//没找到
	return NULL;
}
//在pos位置之后插⼊数据
void LTInsert(LTNode* pos, LTDataType x)
{
	assert(pos);
	LTNode* newNode = LTBuyNode(x);
	//pos newNode pos->next
	newNode->prev = pos;
	newNode->next = pos->next;

	pos->next->prev = newNode;
	pos->next = newNode;
}
//删除pos位置的数据
void LTErase(LTNode* pos)
{
	assert(pos);
	//pos->prev pos pos->next
	pos->prev->next = pos->next;
	pos->next->prev = pos->prev;
	free(pos);
	pos = NULL;
}

void LTDestroy(LTNode* phead)
{
	assert(phead );
	LTNode* cur = phead->next;
	while (cur != phead)
	{
		LTNode* next = cur->next;
		free(cur);
		cur = next;
	}
	free(phead);
	phead = NULL;
}